<script setup lang="ts">
import { reactive, ref } from 'vue'
// 图标
import { User, Lock } from '@element-plus/icons-vue'
// 引入用户相关的仓库数据
import useUserStore from '@/store/modules/user'
// 路由
import { useRouter, useRoute } from 'vue-router'
// el-plus
import { ElNotification } from 'element-plus'
// 工具
import { getTimePeriod } from '@/utils/time'
// 类型
import type { ILoginFormData } from '@/api/login/type'
import type { FormInstance, FormRules } from 'element-plus'
// 路由
const $router = useRouter()
const $route = useRoute()
// 定义用户仓库数据
const userStore = useUserStore()
// 登录表单
let loginForm = reactive<ILoginFormData>({
  username: 'admin',
  password: '111111',
})

// 自定义校验规则
const validatePassword = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length <= 3) {
    callback(new Error('密码长度过短'))
  } else {
    callback()
  }
}

// 表单校验
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 5, message: '用户名不少于5位', trigger: 'change' },
  ],
  password: [{ validator: validatePassword, trigger: 'change' }],
})
// 表单实例
let loginFormRef = ref<FormInstance>()
// 按钮加载标志位
let loading = ref(false)

// 登录
const doLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate()
  try {
    loading.value = true
    await userStore.userLogin(loginForm)
    loading.value = false
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: getTimePeriod(),
    })
    const redirect: any = $route.query.redirect
    $router.push({ path: redirect || '/' })
  } catch (error: unknown) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: error as string,
    })
  }
}
</script>
<template>
  <div class="login-background flex">
    <div class="login-container">
      <div class="title">111</div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="密码"
            type="password"
            show-password
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            @click="doLogin(loginFormRef)"
            @keydown.enter="doLogin(loginFormRef)"
            :loading="loading"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>
